document.addEventListener('DOMContentLoaded', function() {
    var $ = layui.$;
    var layer = layui.layer;
    var upload = layui.upload;
    var table = layui.table;

    // 当前会话ID
    var currentSessionId = null;

    // 文件夹上传
    upload.render({
        elem: '#upload-folder',
        url: '/upload',
        auto: false,
        multiple: true,
        accept: 'file',
        directory: true,
        choose: function(obj) {
            var files = this.files = obj.pushFile();
            var folderName = $('#folder-name').val() || 'SQL文件夹';
            obj.preview(function(index, file, result) {
                $('#file-list').html('');
                $.each(files, function(index, file) {
                    var tr = $(['<tr>'
                        ,'<td>'+ file.name +'</td>'
                        ,'<td>'+ formatFileSize(file.size) +'</td>'
                        ,'<td>等待上传</td>'
                        ,'</tr>'].join(''));
                    tr.data('file', file);
                    $('#file-list').append(tr);
                });
            });
        },
        before: function(obj) {
            var folderName = $('#folder-name').val();
            if (!folderName) {
                layer.msg('请输入文件夹名称', {icon: 2});
                return false;
            }
            layer.load(2);
        },
        done: function(res) {
            layer.closeAll('loading');
            if (res.success) {
                layer.msg('文件上传成功，开始分析...', {icon: 1});
                currentSessionId = res.session_id;
                loadAnalysisResults();
            } else {
                layer.msg(res.error || '上传失败', {icon: 2});
            }
        },
        error: function() {
            layer.closeAll('loading');
            layer.msg('上传失败', {icon: 2});
        }
    });

    // 加载分析结果
    function loadAnalysisResults() {
        if (!currentSessionId) return;

        $.get('/results/' + currentSessionId, function(res) {
            if (res.length === 0) {
                layer.msg('没有找到分析结果', {icon: 2});
                return;
            }

            var tbody = $('#results-body');
            tbody.html('');

            $.each(res, function(index, item) {
                var tr = $('<tr>');
                tr.append('<td>' + item.file_name + '</td>');
                tr.append('<td>' + item.file_size + '</td>');
                tr.append('<td>' + (item.table_names && item.table_names.length > 0 ? item.table_names.join('<br>') : '-') + '</td>');
                tr.append('<td>' + (item.index_names && item.index_names.length > 0 ? item.index_names.join('<br>') : '-') + '</td>');
                tr.append('<td>' + item.updates_last_update + '</td>');
                tr.append('<td>' + item.update_has_where + '</td>');
                tr.append('<td>' + item.delete_has_where + '</td>');
                tr.append('<td>' + item.has_chinese_semicolon + '</td>');
                tr.append('<td>' + item.has_search_path + '</td>');

                // 添加点击查看文件内容事件
                tr.find('td:first').click(function() {
                    var filePath = encodeURIComponent(item.file_path.replace(/\\/g, '/'));
                    window.open('/view_file/' + filePath, '_blank');
                });

                tbody.append(tr);
            });
        }).fail(function() {
            layer.msg('加载分析结果失败', {icon: 2});
        });
    }

    // 搜索功能
    $('#search-btn').click(function() {
        var searchText = $('#search-input').val().toLowerCase();
        if (!searchText) return;

        $('#results-body tr').each(function() {
            var fileName = $(this).find('td:first').text().toLowerCase();
            if (fileName.includes(searchText)) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });

    // 文件大小格式化
    function formatFileSize(bytes) {
        if (bytes < 1024) return bytes + ' B';
        if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
        return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
    }
});
